<template>
  <div class="resident-edit-container">
    <el-card class="resident-edit-card">
      <template #header>
        <div class="card-header">
          <span>编辑住户</span>
          <div class="header-buttons">
            <el-button @click="handleBack">
              <el-icon><ArrowLeft /></el-icon>
              返回列表
            </el-button>
          </div>
        </div>
      </template>
      
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <el-skeleton :rows="10" animated />
      </div>
      
      <!-- 编辑表单 -->
      <div v-else-if="residentData" class="form-area">
        <!-- 房户信息（只读） -->
        <div class="household-info">
          <el-divider content-position="left">房户信息</el-divider>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="所属社区">
                <el-input v-model="residentData.communityName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属楼栋">
                <el-input v-model="residentData.buildingName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="所属单元">
                <el-input v-model="residentData.unitName" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="房户编号">
                <el-input v-model="residentData.roomNumber" readonly />
              </el-form-item>
            </el-col>
          </el-row>
        </div>
        
        <!-- 住户信息表单 -->
        <el-form
          ref="formRef"
          :model="formData"
          :rules="formRules"
          label-width="120px"
          @submit.prevent="handleSubmit"
        >
          <el-divider content-position="left">住户信息</el-divider>
          
          <!-- 基本信息 -->
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="姓名" prop="realName" required>
                <el-input
                  v-model="formData.realName"
                  placeholder="请输入住户姓名"
                  maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="身份证件类型" prop="identityType" required>
                <el-select
                  v-model="formData.identityType"
                  placeholder="请选择证件类型"
                  style="width: 100%"
                >
                  <el-option label="身份证" :value="1" />
                  <el-option label="护照" :value="2" />
                  <el-option label="军官证" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="身份证件号" prop="identityNo" required>
                <el-input
                  v-model="formData.identityNo"
                  placeholder="请输入身份证件号"
                  maxlength="20"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="性别" prop="gender">
                <el-radio-group v-model="formData.gender">
                  <el-radio :value="1">男</el-radio>
                  <el-radio :value="2">女</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="出生日期" prop="birthday">
                <el-date-picker
                  v-model="formData.birthday"
                  type="date"
                  placeholder="请选择出生日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="手机号码" prop="phone">
                <el-input
                  v-model="formData.phone"
                  placeholder="请输入手机号码"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="邮箱" prop="email">
                <el-input
                  v-model="formData.email"
                  placeholder="请输入邮箱地址"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="学历" prop="education">
                <el-select
                  v-model="formData.education"
                  placeholder="请选择学历"
                  style="width: 100%"
                  clearable
                >
                  <el-option label="小学" value="小学" />
                  <el-option label="初中" value="初中" />
                  <el-option label="高中" value="高中" />
                  <el-option label="大专" value="大专" />
                  <el-option label="本科" value="本科" />
                  <el-option label="硕士" value="硕士" />
                  <el-option label="博士" value="博士" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="职业" prop="profession">
                <el-input
                  v-model="formData.profession"
                  placeholder="请输入职业"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="工作单位" prop="workUnit">
                <el-input
                  v-model="formData.workUnit"
                  placeholder="请输入工作单位"
                  maxlength="100"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="籍贯" prop="nativePlace">
                <el-input
                  v-model="formData.nativePlace"
                  placeholder="请输入籍贯"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="紧急联系人" prop="emergencyContact">
                <el-input
                  v-model="formData.emergencyContact"
                  placeholder="请输入紧急联系人"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="紧急联系电话" prop="emergencyPhone">
                <el-input
                  v-model="formData.emergencyPhone"
                  placeholder="请输入紧急联系电话"
                  maxlength="11"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆信息" prop="vehicleInfo">
                <el-input
                  v-model="formData.vehicleInfo"
                  placeholder="请输入车辆信息"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="宠物信息" prop="petInfo">
                <el-input
                  v-model="formData.petInfo"
                  placeholder="请输入宠物信息"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="特殊需求" prop="specialNeeds">
                <el-input
                  v-model="formData.specialNeeds"
                  placeholder="请输入特殊需求"
                  maxlength="200"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 住户房户关联信息 -->
          <el-divider content-position="left">房户关联信息</el-divider>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="住户类型" prop="residentType" required>
                <el-select
                  v-model="formData.residentType"
                  placeholder="请选择住户类型"
                  style="width: 100%"
                >
                  <el-option label="户主" :value="1" />
                  <el-option label="家庭成员" :value="2" />
                  <el-option label="租客" :value="3" />
                  <el-option label="其他" :value="4" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入住日期" prop="moveInDate">
                <el-date-picker
                  v-model="formData.moveInDate"
                  type="date"
                  placeholder="请选择入住日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="搬出日期" prop="moveOutDate">
                <el-date-picker
                  v-model="formData.moveOutDate"
                  type="date"
                  placeholder="请选择搬出日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同开始日期" prop="contractStartDate">
                <el-date-picker
                  v-model="formData.contractStartDate"
                  type="date"
                  placeholder="请选择合同开始日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="合同结束日期" prop="contractEndDate">
                <el-date-picker
                  v-model="formData.contractEndDate"
                  type="date"
                  placeholder="请选择合同结束日期"
                  style="width: 100%"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="月租金" prop="monthlyRent">
                <el-input-number
                  v-model="formData.monthlyRent"
                  placeholder="请输入月租金"
                  style="width: 100%"
                  :min="0"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="押金" prop="deposit">
                <el-input-number
                  v-model="formData.deposit"
                  placeholder="请输入押金"
                  style="width: 100%"
                  :min="0"
                  :precision="2"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="合同编号" prop="contractNo">
                <el-input
                  v-model="formData.contractNo"
                  placeholder="请输入合同编号"
                  maxlength="50"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  v-model="formData.remark"
                  type="textarea"
                  placeholder="请输入备注信息"
                  :rows="3"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 操作按钮 -->
          <el-form-item>
            <el-button type="primary" @click="handleSubmit" :loading="submitting">
              保存
            </el-button>
            <el-button @click="handleBack">取消</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 错误状态 -->
      <div v-else class="error-container">
        <el-empty description="加载住户信息失败">
          <template #description>
            <p>{{ errorMessage }}</p>
          </template>
          <template #extra>
            <el-button type="primary" @click="loadResidentData">重试</el-button>
          </template>
        </el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import { residentApi } from '@/api/resident'

// Router
const router = useRouter()
const route = useRoute()

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const errorMessage = ref('')
const formRef = ref()

// 住户数据
const residentData = ref<any>(null)

// 表单数据
const formData = reactive({
  // 基本信息
  realName: '',
  identityType: 1,
  identityNo: '',
  gender: undefined as number | undefined,
  birthday: undefined as string | undefined,
  phone: '',
  email: '',
  education: '',
  profession: '',
  workUnit: '',
  nativePlace: '',
  emergencyContact: '',
  emergencyPhone: '',
  vehicleInfo: '',
  petInfo: '',
  specialNeeds: '',
  status: 1,
  
  // 住户房户关联信息
  householdId: undefined as number | undefined,
  residentType: 1,
  moveInDate: undefined as string | undefined,
  moveOutDate: undefined as string | undefined,
  contractStartDate: undefined as string | undefined,
  contractEndDate: undefined as string | undefined,
  monthlyRent: undefined as number | undefined,
  deposit: undefined as number | undefined,
  contractNo: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  realName: [
    { required: true, message: '请输入住户姓名', trigger: 'blur' },
    { min: 2, max: 50, message: '姓名长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  identityType: [
    { required: true, message: '请选择身份证件类型', trigger: 'change' }
  ],
  identityNo: [
    { required: true, message: '请输入身份证件号', trigger: 'blur' },
    { min: 15, max: 20, message: '身份证件号长度在 15 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  residentType: [
    { required: true, message: '请选择住户类型', trigger: 'change' }
  ]
}

// 加载住户数据
const loadResidentData = async () => {
  const residentId = route.params.id as string
  if (!residentId) {
    errorMessage.value = '住户ID不能为空'
    return
  }
  
  loading.value = true
  errorMessage.value = ''
  
  try {
    const response = await residentApi.getResidentDetail(parseInt(residentId))
    if (response.code === 200 && response.data) {
      residentData.value = response.data
      
      // 填充表单数据
      Object.assign(formData, {
        realName: response.data.realName || '',
        identityType: response.data.identityType || 1,
        identityNo: response.data.identityNo || '',
        gender: response.data.gender,
        birthday: response.data.birthday,
        phone: response.data.phone || '',
        email: response.data.email || '',
        education: response.data.education || '',
        profession: response.data.profession || '',
        workUnit: response.data.workUnit || '',
        nativePlace: response.data.nativePlace || '',
        emergencyContact: response.data.emergencyContact || '',
        emergencyPhone: response.data.emergencyPhone || '',
        vehicleInfo: response.data.vehicleInfo || '',
        petInfo: response.data.petInfo || '',
        specialNeeds: response.data.specialNeeds || '',
        status: response.data.status || 1,
        householdId: response.data.householdId,
        residentType: response.data.residentType || 1,
        moveInDate: response.data.moveInDate,
        moveOutDate: response.data.moveOutDate,
        contractStartDate: response.data.contractStartDate,
        contractEndDate: response.data.contractEndDate,
        monthlyRent: response.data.monthlyRent,
        deposit: response.data.deposit,
        contractNo: response.data.contractNo || '',
        remark: response.data.remark || ''
      })
    } else {
      errorMessage.value = response.message || '获取住户信息失败'
    }
  } catch (error) {
    console.error('加载住户数据失败:', error)
    errorMessage.value = '加载住户信息失败'
  } finally {
    loading.value = false
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    const residentId = route.params.id as string
    await residentApi.updateResident(parseInt(residentId), formData)
    
    ElMessage.success('住户信息更新成功')
    handleBack()
  } catch (error) {
    if (error !== false) {
      ElMessage.error('更新失败')
    }
  } finally {
    submitting.value = false
  }
}

// 返回列表
const handleBack = () => {
  router.push('/region/resident')
}

// 组件挂载时初始化
onMounted(() => {
  loadResidentData()
})
</script>

<style lang="scss" scoped>
.resident-edit-container {
  padding: 20px;
  
  .resident-edit-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .header-buttons {
        display: flex;
        gap: 10px;
      }
    }
    
    .loading-container {
      padding: 40px 0;
    }
    
    .household-info {
      margin-bottom: 30px;
      padding: 20px;
      background-color: #f8f9fa;
      border-radius: 8px;
      
      .el-form-item {
        margin-bottom: 0;
      }
    }
    
    .form-area {
      .el-divider {
        margin: 30px 0 20px 0;
      }
      
      .el-form-item {
        margin-bottom: 20px;
      }
    }
    
    .error-container {
      text-align: center;
      padding: 60px 0;
      
      p {
        color: #666;
        margin-top: 10px;
      }
    }
  }
}
</style>
